package com.sfy.lotterysystem.service;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.wf.captcha.SpecCaptcha;
@Service
public class CaptchaService {
    private final RedisTemplate<String, String> redisTemplate;

    public CaptchaService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public CaptchaResponse generateCaptcha() {
        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(120, 40, 4); // 宽,高,长度
        String code = captcha.text().toLowerCase();
        String uuid = UUID.randomUUID().toString();

        // 存入redis，5分钟有效
        redisTemplate.opsForValue().set("captcha:" + uuid, code, 5, TimeUnit.MINUTES);

        // 返回图片base64和uuid
        return new CaptchaResponse("data:image/png;base64," + captcha.toBase64(), uuid);
    }

    public boolean validateCaptcha(String uuid, String code) {
        String key = "captcha:" + uuid;
        String realCode = redisTemplate.opsForValue().get(key);
        if (realCode != null && realCode.equalsIgnoreCase(code)) {
            redisTemplate.delete(key); // 验证通过后删除
            return true;
        }
        return false;
    }

    // 内部类用于返回前端
    public static class CaptchaResponse {
        public String img;
        public String uuid;
        public CaptchaResponse(String img, String uuid) {
            this.img = img;
            this.uuid = uuid;
        }
    }
}
